const Role = require('../models/role.model.js')
const util = require('../util/util.js')
const responseResultData = util.responseResultData
// 创建新的角色对象
exports.create = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  if (!req.body.name) {
    responseResultData(res, 200, false,  '名称不能为空', '')
    return
  }
  // 创建新的对象
  const roleModel = Role.createNew({
    name: req.body.name,
    remark: req.body.remark ?? ''
  })
  Role.create([roleModel], (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '创建角色错误', '')
      return
    }
    responseResultData(res, 200, true, '', '')
  })
  
}
// 根据ID查询角色
exports.getDetail = (req, res) => {
  // 验证请求
  if (!req.query || !req.query.id) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }

  // 查找
  Role.getById(req.query.id, (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '查找角色错误', '')
      return
    }
    if(!data) {
      responseResultData(res, 200, false, '未找到角色信息')
      return
    }
    responseResultData(res, 200, true, '', data)
  })
}
// 获取角色列表
exports.getList = (req, res) => {
  // 查找所有
  Role.getList((err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '获取角色列表错误', '')
      return
    }
    responseResultData(res, 200, true, '', data)
  })
}

// 根据ID更新角色
exports.update = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  if (!req.body.name) {
    responseResultData(res, 200, false,  '名称不能为空', '')
    return
  }
  const body = {
    id: req.body.id,
    name: req.body.name,
    remark: req.body.remark ?? '',
  }
  // 更新
  Role.updateById(body, (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '更新角色错误', '')
      return
    }
    responseResultData(res, 200, true, '', data)
  })

}
// 删除角色
exports.delete = (req, res) => {
  // 验证请求
  if (!req.body || !req.body.id) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  // 删除
  Role.delete(req.body.id, (err) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '删除角色错误', '')
      return
    }
    responseResultData(res, 200, true, '', '')
  })
}
// 设置权限
exports.setNavigation = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  
}

